package com.ruoyi.fs.service.impl;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.fs.domain.*;
import com.ruoyi.fs.mapper.*;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.fs.service.IFsCaseService;

/**
 * 案件信息Service业务层处理
 *
 * @author hero
 * @date 2024-08-30
 */
@Service
public class FsCaseServiceImpl implements IFsCaseService {
    @Autowired
    private FsCaseMapper fsCaseMapper;
    @Autowired
    private FsLayerTeamMapper fsLayerTeamMapper;
    @Autowired
    private FsTimeLineMapper fsTimeLineMapper;
    @Autowired
    private FsBatchMapper fsBatchMapper;
    @Autowired
    private FsEntrustMapper fsEntrustMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    private static DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static String lazt = "fs_gw_layyzt";

    private static String ajzt = "fs_gw_ajzt";

    /**
     * 查询案件信息
     *
     * @param id 案件信息主键
     * @return 案件信息
     */
    @Override
    public FsCase selectFsCaseById(Long id) {
        return fsCaseMapper.selectFsCaseById(id);
    }

    /**
     * 查询案件信息
     *
     * @param bh 案件信息主键
     * @return 案件信息
     */
    @Override
    public FsCase selectFsCaseByBh(String bh) {
        FsCase query = new FsCase();
        query.setBh(bh);
        List<FsCase> list = fsCaseMapper.selectFsCaseList(query);
        if (list.isEmpty()) {
            return null;
        } else {
            return list.get(0);
        }
    }

    @Override
    public FsCase selectFsCaseByNbbh(String bh) {
        if (StringUtils.isBlank(bh)) {
            return null;
        }
        FsCase query = new FsCase();
        query.setNbajbh(bh);
        List<FsCase> list = fsCaseMapper.selectFsCaseList(query);
        if (list.isEmpty()) {
            return null;
        } else {
            return list.get(0);
        }
    }

    /**
     * 查询案件信息
     *
     * @param ah 案件信息主键
     * @return 案件信息
     */
    @Override
    public FsCase selectFsCaseByAh(String ah) {
        FsCase query = new FsCase();
        query.setAh(ah);
        List<FsCase> list = fsCaseMapper.selectFsCaseList(query);
        if (list.isEmpty()) {
            return null;
        } else {
            return list.get(0);
        }
    }

    /**
     * 查询案件信息列表
     *
     * @param fsCase 案件信息
     * @return 案件信息
     */
    @Override
    public List<FsCase> selectFsCaseList(FsCase fsCase) {
        return fsCaseMapper.selectFsCaseList(fsCase);
    }

    /**
     * 新增案件信息
     *
     * @param fsCase 案件信息
     * @return 结果
     */
    @Override
    public int insertFsCase(FsCase fsCase) {
        fsCase.setCreateTime(DateUtils.getNowDate());
        int result = fsCaseMapper.insertFsCase(fsCase);
        addTimeLineForNewCase(fsCase);
        if (fsCase.getBatchId() != null) {
            BigDecimal bdje = fsCase.getSqbdje();
            FsBatch batch = fsBatchMapper.selectFsBatchById(fsCase.getBatchId());
            FsEntrust entrust = fsEntrustMapper.selectFsEntrustById(batch.getZfid());
            batch.setCaseCount(batch.getCaseCount() + 1);
            entrust.setCaseCount(entrust.getCaseCount() + 1);
            batch.setWtze(batch.getWtze().add(bdje));
            entrust.setWtze(entrust.getWtze().add(bdje));
            fsBatchMapper.updateFsBatch(batch);
            fsEntrustMapper.updateFsEntrust(entrust);
        }
        return result;
    }

    /**
     * 修改案件信息
     *
     * @param fsCase 案件信息
     * @return 结果
     */
    @Override
    public int updateFsCase(FsCase fsCase) {
        fsCase.setUpdateTime(DateUtils.getNowDate());
        addTimeLineForEditCase(fsCase, false, null);
        int result = fsCaseMapper.updateFsCase(fsCase);
        return result;
    }

    /**
     * 批量删除案件信息
     *
     * @param ids 需要删除的案件信息主键
     * @return 结果
     */
    @Override
    public int deleteFsCaseByIds(Long[] ids) {
        return fsCaseMapper.deleteFsCaseByIds(ids);
    }

    /**
     * 删除案件信息信息
     *
     * @param id 案件信息主键
     * @return 结果
     */
    @Override
    public int deleteFsCaseById(Long id) {
        return fsCaseMapper.deleteFsCaseById(id);
    }

    @Override
    public void assignment(Long caseId) {
        FsCase fsCase = fsCaseMapper.selectFsCaseById(caseId);
        assignment(fsCase);
    }

    @Override
    public void assignment(FsCase fsCase) {
        if (fsCase.getTjyId() != null) {
            return;
        }
        Long lsid = fsCase.getOwnerId();
        FsLayerTeam team = new FsLayerTeam();
        team.setLsid(lsid);
        List<FsLayerTeam> teams = fsLayerTeamMapper.selectFsLayerTeamList(team);
        int min = 0;
        FsLayerTeam minTeam = null;
        Long tjyId = null;
        if (!teams.isEmpty()) {
            for (int i = 0; i < teams.size(); i++) {
                FsLayerTeam layerTeam = teams.get(i);
                if (min == 0 || min > layerTeam.getTotalCaseNum()) {
                    minTeam = layerTeam;
                    min = layerTeam.getTotalCaseNum();
                    tjyId = layerTeam.getTjyid();
                }
            }
            SysUser user = sysUserMapper.selectUserById(tjyId);
            fsCase.setTjyId(tjyId);
            fsCase.setTjy(user.getNickName());
            fsCaseMapper.updateFsCase(fsCase);
            min++;
            minTeam.setTotalCaseNum(min);
            fsLayerTeamMapper.updateFsLayerTeam(minTeam);
        }
    }

    @Override
    public void addTimeLineForEditCase(FsCase fsCase, boolean ifSd, SysUser user) {
        FsCase old = fsCaseMapper.selectFsCaseById(fsCase.getId());
        String content = "";
        if (!fsCase.getBh().equals(old.getBh())) {
            content = "重新立案";
        }
        if (fsCase.getAjzt() != null && fsCase.getAjzt() == old.getAjzt()) {
            if (fsCase.getAjzt() == 0) {
                if (fsCase.getZt() != old.getZt()) {
                    String oldStr = sysDictDataMapper.selectDictLabel(lazt, old.getZt() + "");
                    String newStr = sysDictDataMapper.selectDictLabel(lazt, fsCase.getZt() + "");
                    content = "立案状态变更：" + oldStr + " -> " + newStr;
                }
            } else {
                return;
            }
        } else if (old.getAjzt() != null && fsCase.getAjzt() != old.getAjzt()) {
            String oldStr = sysDictDataMapper.selectDictLabel(ajzt, old.getAjzt() + "");
            String newStr = sysDictDataMapper.selectDictLabel(ajzt, fsCase.getAjzt() + "");
            content = "案件状态变更：" + oldStr + " -> " + newStr;
        }
        if (StringUtils.isBlank(content)) {
            return;
        }
        FsTimeLine line = new FsTimeLine();
        line.setCaseId(old.getId());
        String gxsj = fsCase.getGxsj();
        Date d = new Date();
        try {
            if (StringUtils.isNotBlank(gxsj)) {
                if (gxsj.length() > 11) {
                    d = df.parse(gxsj);
                } else {
                    d = sdf.parse(gxsj);
                }
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        line.setDate(d);
        line.setType(1);
        line.setTitle("案件状态更新");
        line.setContent(content);
        if (ifSd && user != null) {
            line.setOwner(user.getNickName());
        }
        line.setBatchName(fsCase.getBatchName());
        fsTimeLineMapper.insertFsTimeLine(line);
    }


    public void addTimeLineForNewCase(FsCase fsCase) {
        FsTimeLine line = new FsTimeLine();
        line.setCaseId(fsCase.getId());
        String gxsj = fsCase.getGxsj();
        Date d = new Date();
        try {
            if (StringUtils.isNotBlank(gxsj)) {
                if (gxsj.length() > 11) {
                    d = df.parse(gxsj);
                } else {
                    d = sdf.parse(gxsj);
                }
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        line.setDate(d);
        line.setType(1);
        line.setTitle("案件初始化");
        String content = "";
        if (fsCase.getZt() == 1) {
            content = "初次提网立案";
        } else {
            content = "初次从人民法院律师服务平台同步案件";
        }
        line.setContent(content);
        fsTimeLineMapper.insertFsTimeLine(line);
    }
}
